<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Crypt;
use Hash;
use DB;

class UserController extends Controller
{
    public function __construct()
    {
        $this -> middleware('login');
    }
    //
    public function add()
    {
    	return view('admin.user.add',['title' => '用户添加']);
    }

    public function insert(Request $request)
    {
    	$this -> validate($request, [
    		'username' => 'required|between:6,18',
    		'password' => 'required|min:6|max:18',
    		'repassword' => 'same:password',
    		'email' => 'email',
    		'phone' => 'digits:11',
    		'picname' => 'image|max:2048'
    		// 'picname' => 'required|image|max:2048'
    	],[
    		'username.required' =>'用户名为必填项!',
    		'username.between' => '用户名要求6到18位!',
    		'password.required' =>'密码为必填项!',
    		'password.min' => '至少6位密码',
    		'password.max' => '最多18位密码',
    		'repassword.same' => '与第一次密码不一致',
    		'email.email' => '请输入正确的邮箱地址',
    		'phone.digits' => '请输入正确的11位手机号',
    		// 'picname.required' => '你必须上传一张图片',
    		'picname.image' => '你必须上传一张图片',
    		'picname.size' =>  '最大10M'
    	]);


    	$data = $request -> except('_token','repassword');

    	$userData['username'] = $data['username'];
    	$userData['email'] = $data['email'];
    	$userData['phone'] = $data['phone'];
    	//处理密码字段
    	$userData['password'] = Crypt::encryptString($data['password']);
    	// return Crypt::decryptString($str);
    	 // $str= Hash::make($data['password']);
    	 // // return $str;
    	 // $res = Hash::check($data['password'], $str);
    	 // var_dump($res);
    	if($request -> hasFile('picname'))
    	{
    		if($request -> file('picname') -> isValid())
    		{
    			//处理头像
		    	// getClientOriginalExtension()    extension()
		    	$extension = $request -> file('picname') -> getClientOriginalExtension();
		    	// echo $extension;
		    	$filename = mt_rand(1000000,9999999).'.'.$extension;
		    	$dir = './uploads/avatar/';

		    	$request -> file('picname') -> move($dir,$filename);//storeAs
    			$userInfoData['picname'] = '/uploads/avatar/'.$filename;
    		}
    	}else
    	{
    		$userInfoData['picname'] = '/uploads/avatar/default.jpg';
    	}
    	
    	$userData['token'] = str_random(50);
    	$userData['airline'] = 0;
    	$userData['status'] = 0;
    	$time = Date('Y-m-d H:i:s');
    	$userData['created_at'] = $time;
    	$userData['updated_at'] = $time;

    	//添加数据   //要求用事务处理
    	$userId = DB::table('users') -> insertGetId($userData);
    	if($userId)
    	{
    		$userInfoData['uid'] = $userId;
    		$userInfoData['created_at'] = $time;
    		$userInfoData['updated_at'] = $time;

    		$res = DB::table('users_info') -> insert($userInfoData);

    		if($res)
    		{
    			return redirect('/admin/user/index') -> with(['info' => '添加成功']);
    		}else
    		{
    			return back() -> with(['info' => '添加失败']);
    		}
    	}

    	// dd($userData);
    	// dd($data);
    }

    //index
    public function index(Request $request)
    {

    	$num = $request -> input('num',10);
    	$keywords = $request -> input('keywords',''); 
    	$data = DB::table('users') 
    		-> select('users.*','users_info.picname')
    		-> leftJoin('users_info','users.id','=','users_info.uid')
    		-> where('username','like','%'.$keywords.'%')
    		-> paginate($num);
    	// dd($data);
 
    	return view('admin.user.index',['data' => $data,'request' => $request ->all(),'title' => '用户列表']);
    }


    public function changeName(Request $request)
    {	
    	$id = $request -> id;
    	$username = $request -> username;

    	$res = DB::table('users') -> where('id', $id) -> update(['username' => $username]);
    	
    	if($res)
    	{
    		return 1;
    	}else
    	{
    		return 0;
    	}

    	// return 'abc';
    }

    public function edit($id)
    {
    	$data = DB::table('users') 
    		-> select('users.*','users_info.picname')
    		-> leftJoin('users_info','users.id','=','users_info.uid')
    		-> where('users.id','=',$id)
    		-> first();

    	return view('admin.user.edit',['title' => '用户编辑','data' => $data]);

    }

    public function update(Request $request)
    {	
    	//一个验证的方法
    	$this -> validate($request, [
    		'username' => 'required|between:6,18',
    		'email' => 'email',
    		'phone' => 'digits:11',
    		'picname' => 'image|max:2048'
    		// 'picname' => 'required|image|max:2048'
    	],[
    		'username.required' =>'用户名为必填项!',
    		'username.between' => '用户名要求6到18位!',
    		'email.email' => '请输入正确的邮箱地址',
    		'phone.digits' => '请输入正确的11位手机号',
    		// 'picname.required' => '你必须上传一张图片',
    		'picname.image' => '你必须上传一张图片',
    		'picname.size' =>  '最大10M'
    	]);

    	$id = $request -> id;

    	$data = $request -> except('_token','id','picname');

    	
    	if($request -> hasFile('picname'))
    	{
    		if($request -> file('picname') -> isValid())
    		{
    			//处理头像
		    	// getClientOriginalExtension()    extension()
		    	$extension = $request -> file('picname') -> getClientOriginalExtension();
		    	// echo $extension;
		    	$filename = mt_rand(1000000,9999999).'.'.$extension;
		    	$dir = './uploads/avatar/';

		    	$request -> file('picname') -> move($dir,$filename);//storeAs
    			$userInfoData['picname'] = '/uploads/avatar/'.$filename;
    			//获取原来的图片地址
    			$oldPicname = DB::table('users_info') -> where('uid',$id) -> first() -> picname;
    			if(!empty($oldPicname))
    			{
    				if($oldPicname != '/uploads/avatar/default.jpg')
    				{	

    					// if($oldPicname == '/' || $oldPicname =='./')//自己加的判断防误删
    					// 	{
    					// 		return;
    					// 	}
    					if(file_exists('.'.$oldPicname))
    					{
    						unlink('.'.$oldPicname);
    					}
    				}
    			}

    			DB::table('users_info') ->where(['uid' => $id]) -> update($userInfoData);
    			// var_dump($userInfoData);
    		}
    	}else
    	{
    		$userInfoData['picname'] = '/uploads/avatar/default.jpg';
    	}
    	//修改
    	$res = DB::table('users') -> where('id',$id) ->update($data);
    	
    	if($res)
    	{
    		return redirect('/admin/user/index') -> with(['info' => '修改成功']);
    	}else
    	{
    		return back() -> with(['info' => '修改失败']);
    	}
    }


    //delete
    public function delete($id)
    {
    	$picname = DB::table('users_info') -> where('id',$id) ->first() ->picname;
    	$res = DB::table('users') -> where('id',$id) -> delete();
    	$oldPicname = DB::table('users_info') -> where('uid',$id) -> first() -> picname;
    	if($res)
    	{
    		DB::table('users_info') ->where('uid',$id) -> delete();
    		if(!empty($oldPicname))
			{
				if($oldPicname != '/uploads/avatar/default.jpg')
				{	

					if(file_exists('.'.$oldPicname))
					{
						unlink('.'.$oldPicname);
					}
				}
			}
    	}
		if($res)
		{
    		return redirect('/admin/user/index') -> with(['info' => '删除成功']);
    	}else
    	{
    		return back() -> with(['info' => '删除失败']);
    	}  		

    }

}
